package com.lb.shopguide.ui.fragment.guide.recommend;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.flyco.tablayout.SlidingTabLayout;
import com.google.gson.JsonArray;
import com.google.zxing.WriterException;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterMaterialGoods;
import com.lb.shopguide.adapter.AdapterRecActivity;
import com.lb.shopguide.adapter.viewpager.AdapterRecommendType;
import com.lb.shopguide.base.BaseFragment;
import com.lb.shopguide.base.BaseMainFragment;
import com.lb.shopguide.config.AppConfigManager;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.AlipayAccountBean;
import com.lb.shopguide.entity.UserBean;
import com.lb.shopguide.entity.recommend.ActivityBannerBean;
import com.lb.shopguide.entity.recommend.MaterialGoodsBean;
import com.lb.shopguide.entity.recommend.RecBannerBean;
import com.lb.shopguide.entity.recommend.ZoneTypeBean;
import com.lb.shopguide.entity.trace.TraceBean;
import com.lb.shopguide.event.guide.ActivityFinishEvent;
import com.lb.shopguide.event.guide.BindAlipayEvent;
import com.lb.shopguide.event.guide.FansTransToMemberEvent;
import com.lb.shopguide.event.guide.StartBrotherEvent;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.shopguide.trace.TraceManager;
import com.lb.shopguide.ui.activity.ActivityActivityDetail;
import com.lb.shopguide.ui.activity.ActivityRecommendGuide;
import com.lb.shopguide.ui.dialog.DialogShare2Circle;
import com.lb.shopguide.ui.dialog.DialogZoneToast;
import com.lb.shopguide.ui.fragment.guide.pay.FragmentSetAlipayAccount;
import com.lb.shopguide.ui.view.ViewPagerForScrollView;
import com.lb.shopguide.util.FileUtilsExt;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.AdJumpUtil;
import com.lb.shopguide.util.lb.BarcodeUtil;
import com.lb.shopguide.util.lb.BizUtil;
import com.lb.shopguide.util.pic.ImageLoaderUtils;
import com.qmuiteam.qmui.util.QMUIDrawableHelper;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Create by kangzhao on 2018/11/17
 */
public class FragmentRecommendHome extends BaseMainFragment {
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tabs)
    SlidingTabLayout mTabLayout;
    @BindView(R.id.viewPager)
    ViewPagerForScrollView mViewPager;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R.id.tv_acount)
    TextView tvAccount;
    @BindView(R.id.tv_month_sale)
    TextView tvMonthSale;
    @BindView(R.id.tv_today_sale_count)
    TextView tvTodaySaleCount;
    @BindView(R.id.tv_all_money)
    TextView tvAllMoney;
    @BindView(R.id.tv_not_get_money)
    TextView tvNotGetMoney;
    @BindView(R.id.tv_order_entrance)
    TextView tvOrderEntrance;
    @BindView(R.id.layout_earn_secret)
    LinearLayout layoutEarnSecret;
    @BindView(R.id.iv_earn_secret)
    ImageView ivEarnSecret;
    @BindView(R.id.rv_recommend_material)
    RecyclerView recyclerViewMaterial;
    @BindView(R.id.rv_activity)
    RecyclerView rvActivitys;
    @BindView(R.id.layout_share_image)
    LinearLayout layoutShareImage;
    private List<ZoneTypeBean> mZoneTypeList;
    private AdapterRecommendType mAdapterRecommendType;

    private List<MaterialGoodsBean> mMaterialGoodsList;
    private AdapterMaterialGoods mAdapterMaterialsGoods;

    private List<ActivityBannerBean> mActivityList;
    private AdapterRecActivity mAdapterRecActivity;

    private MaterialGoodsBean mMaterialGoodsBean;
    private String shareUrl;
    private boolean isBindAlipay;
    private LoadingDialog ld;

    private boolean firstIn = false;
    private boolean toastFlag = false;
    //    private List<String> imgList;
    private MaterialHeader mMaterialHeader;

    public static FragmentRecommendHome newInstance() {
        return new FragmentRecommendHome();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_recommend_home;
    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);
        sendRequestGetMaterial();
        refresh();
    }

    private void refresh() {
//        imgList = new ArrayList<>();
        mActivityList = new ArrayList<>();
        mZoneTypeList = new ArrayList<>();
        mMaterialGoodsList = new ArrayList<>();
        sendRequestGetAlipayAccount();
        sendRequestGetStaffInfo();
        getSalesStatistics();
        getListProductZone();
        getListMaterialProduct();
        sendRequestGetActivityProgress();
    }

    @Override
    public void initView() {
        mMaterialHeader = (MaterialHeader) refreshLayout.getRefreshHeader();
        mMaterialHeader.setColorSchemeColors(Color.rgb(253, 91, 89));
        mAdapterMaterialsGoods = new AdapterMaterialGoods(R.layout.item_material_goods, mMaterialGoodsList, this);
        recyclerViewMaterial.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerViewMaterial.setAdapter(mAdapterMaterialsGoods);

        recyclerViewMaterial.setHasFixedSize(true);
        recyclerViewMaterial.setNestedScrollingEnabled(false);


        mAdapterRecActivity = new AdapterRecActivity(R.layout.item_rec_activity_item, mActivityList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvActivitys.setLayoutManager(layoutManager);
        rvActivitys.setAdapter(mAdapterRecActivity);

        ImageLoaderUtils.displayGif(R.drawable.shake, ivEarnSecret);
        initListener();

        refreshLayout.setEnableOverScrollDrag(false);
    }

    private void initListener() {
        mAdapterMaterialsGoods.setOnMaterialListener(new AdapterMaterialGoods.OnMaterialListener() {
            @Override
            public void onShareCircle(MaterialGoodsBean bean) {
                ld = new LoadingDialog(mContext);
                ld.setLoadingText("处理中")
                        .setInterceptBack(true)
                        .setLoadSpeed(LoadingDialog.Speed.SPEED_ONE)
                        .show();
                ld.show();
                mMaterialGoodsBean = bean;
                ImageView ivGoods = layoutShareImage.findViewById(R.id.iv_goods);
                ImageView ivBarcode = layoutShareImage.findViewById(R.id.iv_barcode);
                boolean result = BizUtil.copyToClipboard(mContext, bean.getMatText());
                int orderEntranceCode = AppConstant.MATERIAL_GOODS;
                if (AppConfigManager.getAppconfigManager(mContext).getDevMode() == AppConstant.KEY_RUN_MODE_FORMAL) {
                    shareUrl = "https://singlepage.storeer.com/activity_2018/eightHalf_index?productCode=" + mMaterialGoodsBean.getProductCode() + "&appEntranceType=" +
                            AppConstant.APP_ENTRANCE_ANDROID + "&linkStaffCode=" + mUserConfigManager.getUserId() + "&xd_code=XD0008" + "&orderEntryCode=" + orderEntranceCode + "&productType=" + AppConstant.PTYPE_MATERIAL_GOODS;
                } else {
                    shareUrl = "https://sintest.storeer.com/activity_2018/eightHalf_index?productCode=" + mMaterialGoodsBean.getProductCode() + "&appEntranceType=" +
                            AppConstant.APP_ENTRANCE_ANDROID + "&linkStaffCode=" + mUserConfigManager.getUserId() + "&xd_code=XD0008" + "&orderEntryCode=" + orderEntranceCode + "&productType=" + AppConstant.PTYPE_MATERIAL_GOODS;
                }
                try {
                    Bitmap bitmap = BarcodeUtil.createQRCode(shareUrl, SizeUtils.dp2px(95));
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                    byte[] bytes = baos.toByteArray();
                    RequestOptions requestOptions = new RequestOptions()
                            .fitCenter()
                            .error(R.drawable.iv_default_avatar)
                            .priority(Priority.HIGH)
                            .diskCacheStrategy(DiskCacheStrategy.NONE);
                    ImageLoaderUtils.getGlideManager().load(bytes).apply(requestOptions).into(ivBarcode);
                } catch (WriterException e) {
                    e.printStackTrace();
                }
                TextView tvGoodsName = layoutShareImage.findViewById(R.id.tv_share_goods_name);
                TextView tvOriginPrice = layoutShareImage.findViewById(R.id.tv_share_price_origin);
                tvOriginPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                TextView tvSalePrice = layoutShareImage.findViewById(R.id.tv_share_price);
                LinearLayout layoutLimit = layoutShareImage.findViewById(R.id.layout_sec);
                TextView tvLimitTime = layoutShareImage.findViewById(R.id.tv_limit_time);
                TextView tvSaleHour = layoutShareImage.findViewById(R.id.tv_sale_hour);
                if (bean.isSecSymbol()) {
                    if (bean.getSecStatus() == AppConstant.GOODS_SEC_NOT_START) {
                        Date date = TimeUtils.millis2Date(bean.getSecBeginTimeStamp());
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(date);
                        if (TimeUtils.isToday(date)) {
                            tvLimitTime.setText("今天 " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + "开始");
                        } else {
                            tvLimitTime.setText(cal.get(Calendar.MONTH) + 1 + "-" + cal.get(Calendar.DAY_OF_MONTH) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + "开始");
                        }
                        tvSaleHour.setVisibility(View.VISIBLE);
                        long period = bean.getSecEndTimeStamp() - bean.getSecBeginTimeStamp();
                        tvSaleHour.setText("仅售卖" + BizUtil.formatDuring(period));
                    } else if (bean.getSecStatus() == AppConstant.GOODS_SEC_START) {
                        Date date = TimeUtils.millis2Date(bean.getSecEndTimeStamp());
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(date);
                        if (TimeUtils.isToday(date)) {
                            tvLimitTime.setText("今天 " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + "结束");
                        } else {
                            tvLimitTime.setText(cal.get(Calendar.MONTH) + 1 + "-" + cal.get(Calendar.DAY_OF_MONTH) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + "结束");
                        }
                        tvSaleHour.setVisibility(View.GONE);
                    }
                    layoutLimit.setVisibility(View.VISIBLE);
                } else {
                    layoutLimit.setVisibility(View.GONE);
                }
                ImageLoaderUtils.display(mContext, ivGoods, bean.getSharePicUrls().get(bean.getSharePicUrls().size() - 1));
                tvGoodsName.setText(bean.getProductName());
                tvOriginPrice.setText("￥" + bean.getOrgPrice());
                tvSalePrice.setText("￥" + bean.getSalePrice());
                SpannableString sp = new SpannableString(tvSalePrice.getText().toString());
                sp.setSpan(new RelativeSizeSpan(0.5f), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //0.5f表示
                tvSalePrice.setText(sp);
                if (result) {
                    ivBarcode.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ld.close();
                            showShareDialog();
                        }
                    }, 1500);
                }
                if (result) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            List<String> urls = bean.getSharePicUrls();
                            for (int i = 0; i < urls.size(); i++) {
                                String name = i + bean.getProductCode() + AppConstant.PNG;
                                if (i != urls.size() - 1) {
                                    FileUtilsExt.saveImageToGallery(mContext, name, BizUtil.getBitmapByUrl(BizUtil.addSlimParam(urls.get(i))));
                                }else {
                                   FileUtilsExt.saveImageToGallery(mContext, name, QMUIDrawableHelper.createBitmapFromView(layoutShareImage));
                                }
                            }
//                            Message msg = Message.obtain();
//                            msg.what = 0;
//                            myHandler.sendMessageDelayed(msg, 500);
                        }
                    }).start();
                }
            }

            @Override
            public void viewImage(int position, List<String> urls) {
                EventBus.getDefault().post(new StartBrotherEvent(FragmentGoodsImage.newInstance(position, urls)));
            }
        });
        mAdapterRecActivity.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (mActivityList.size() > position) {
                    ActivityBannerBean bean = mActivityList.get(position);
                    String truePath = BizUtil.fixActivityUrl(bean.getActLinkPath(), "XD0009");
                    Intent intent = new Intent(getContext(), ActivityActivityDetail.class);
                    Bundle bundle = new Bundle();
                    bundle.putString(AppConstant.WEB_URL, truePath);
                    bundle.putString(AppConstant.WEB_TITLE, "");
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                EventBus.getDefault().post(new StartBrotherEvent(FragmentPlayVideo.newInstance()));
                refresh();
                refreshLayout.finishRefresh();
            }
        });
    }


    private void jumpLogic(RecBannerBean bean) {
        BaseFragment fragment = AdJumpUtil.jumpToDestination(bean.getJumpMode(), bean.getPageSdCode(), bean.getRelCode(), bean.getRelName(), bean.getJumpUrl());
        if (fragment instanceof FragmentRecommendHome) {
        } else if (fragment instanceof FragmentVirtualActivity) {
            Intent intent = new Intent(getContext(), ActivityActivityDetail.class);
            Bundle bundle = new Bundle();
            bundle.putString(AppConstant.WEB_URL, fragment.getArguments().getString(AppConstant.WEB_URL));
            bundle.putString(AppConstant.WEB_TITLE, fragment.getArguments().getString(AppConstant.WEB_TITLE));
            intent.putExtras(bundle);
            startActivity(intent);
        } else {
            EventBus.getDefault().post(new StartBrotherEvent(fragment));
        }
    }

    @SuppressLint("HandlerLeak")
    Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                ld.close();
                showShareDialog();
            }
        }
    };

    private void showShareDialog() {
        DialogShare2Circle dialogShare2Circle = DialogShare2Circle.getDialogShare2Circle(AppConstant.BANNER_TYPE_SHARE_MATERIAL, mMaterialGoodsBean.getProductCode());
        dialogShare2Circle.show(getFragmentManager(), getPageTag());
        dialogShare2Circle.setOnDialogClickListener(new DialogShare2Circle.OnDialogClickListener() {
            @Override
            public void onBannerClick(RecBannerBean bean) {
                dialogShare2Circle.dismissAllowingStateLoss();
                jumpLogic(bean);
            }

            @Override
            public void onShareCircle() {
                BizUtil.jumpToWechat(mContext);
            }
        });
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {

    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }

    @Override
    public String getPageTag() {
        return FragmentRecommendHome.class.getCanonicalName();
    }


    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (toastFlag) {
            sendRequestGetIntervalHint();
            toastFlag = false;
        }
        if (firstIn) {
            toastFlag = true;
            firstIn = false;
            Intent intent = new Intent(mContext, ActivityRecommendGuide.class);
            startActivity(intent);
        }
        UserConfigManager userConfigManager = UserConfigManager.getInstance(mContext);
        if (!userConfigManager.isRecOpen()) {
            userConfigManager.setRecOpen(true);
            userConfigManager.save2Sp(true);
            firstIn = true;
            TraceBean bean = new TraceBean();
            bean.setXdCode("XD0007");
            bean.setYdCode("YD0009");
            TraceManager.getTraceManager(mContext).trackFinishGuide(bean);
            EventBus.getDefault().post(new StartBrotherEvent(FragmentPlayVideo.newInstance()));
        }
    }

    @OnClick(R.id.tv_order_entrance)
    void enterOrder() {
        EventBus.getDefault().post(new StartBrotherEvent(FragmentRecommendOrderList.newInstance()));
    }

    @OnClick(R.id.layout_earn_secret)
    void secretClick() {
        String url = "";
        if (AppConfigManager.getAppconfigManager(mContext).getDevMode() == AppConstant.KEY_RUN_MODE_FORMAL) {
            url = "https://singlepage.storeer.com/activity_2018/eightHalf_guide_help";
        } else {
            url = "https://sintest.storeer.com/activity_2018/eightHalf_guide_help";
        }
        startToActivityPage(url, "赚钱秘籍");
    }


    @OnClick(R.id.tv_acount)
    void bindAlipay() {
        if (!isBindAlipay) {
            EventBus.getDefault().post(new StartBrotherEvent(FragmentSetAlipayAccount.newInstance(AppConstant.SET_ALIPAY_ACCOUNT)));
        }
    }

    private void startToActivityPage(String url, String name) {
        Intent intent = new Intent(mContext, ActivityActivityDetail.class);
        Bundle bundle = new Bundle();
        if (url.contains("?")) {
            bundle.putString(AppConstant.WEB_URL, url + "&token=" + mUserConfigManager.getUserToken() + "&type=android");
        } else {
            bundle.putString(AppConstant.WEB_URL, url + "?token=" + mUserConfigManager.getUserToken() + "&type=android");
        }
        bundle.putString(AppConstant.WEB_TITLE, name);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private void bindType() {
        mAdapterRecommendType = new AdapterRecommendType(getChildFragmentManager(), mZoneTypeList);
        mViewPager.setAdapter(mAdapterRecommendType);
        mViewPager.setOffscreenPageLimit(4);
        mTabLayout.setViewPager(mViewPager);
    }

    private void bindMaterialGoods() {
        recyclerViewMaterial.setVisibility(View.VISIBLE);
        mAdapterMaterialsGoods.setNewData(mMaterialGoodsList);
    }

    private void bindActivitys() {
        rvActivitys.setVisibility(View.VISIBLE);
        mAdapterRecActivity.setNewData(mActivityList);
    }

    private void bindSaleData(String monthSalesMoney, int dayOrderNum, String totalBonusMoney, String notTransferBonusMoney) {
        tvMonthSale.setText(monthSalesMoney);
        tvTodaySaleCount.setText("" + dayOrderNum);
        tvAllMoney.setText(totalBonusMoney);
        tvNotGetMoney.setText(notTransferBonusMoney);
    }

    @OnClick(R.id.tv_material_load_more)
    void moreClick() {
        EventBus.getDefault().post(new StartBrotherEvent(FragmentMaterialGoods.newInstance()));
    }

    private void showZoneToast() {
        DialogZoneToast dialog = DialogZoneToast.getDialogZoneToast();
        dialog.show(getFragmentManager(), getPageTag());
    }


    private void getSalesStatistics() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(response.getReturnContent().toString());
                        String monthSalesMoney = jsonObject.getString("monthSalesMoney");
                        int dayOrderNum = jsonObject.getInt("dayOrderNum");
                        String totalBonusMoney = jsonObject.getString("totalBonusMoney");
                        String notTransferBonusMoney = jsonObject.getString("notTransferBonusMoney");
                        bindSaleData(monthSalesMoney, dayOrderNum, totalBonusMoney, notTransferBonusMoney);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        ApiMethodGuide.getSalesStatistics(new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }

    private void getListProductZone() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JsonArray jsonArray = JsonUtil.getJsonArrayFromMap(response.getReturnContent());
                    for (int i = 0; i < jsonArray.size(); i++) {
                        ZoneTypeBean bean = JsonUtil.getGson().fromJson(jsonArray.get(i), ZoneTypeBean.class);
                        mZoneTypeList.add(bean);
                    }
                    bindType();
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
            }
        };
        ApiMethodGuide.listProductZone(new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }

    private void getListMaterialProduct() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JsonArray jsonArray = JsonUtil.getJsonArrayFromMap(response.getReturnContent());
                    for (int i = 0; i < jsonArray.size(); i++) {
                        MaterialGoodsBean bean = JsonUtil.getGson().fromJson(jsonArray.get(i), MaterialGoodsBean.class);
                        mMaterialGoodsList.add(bean);
                    }
                    bindMaterialGoods();
                } else {
                    ToastUtils.showShort(response.getMessage());
                    recyclerViewMaterial.setVisibility(View.GONE);
                }
            }
        };
        ApiMethodGuide.listMaterialProductInHome(new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestGetActivityProgress() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JsonArray jsonArray = JsonUtil.getJsonArrayFromMap(response.getReturnContent());
                    for (int i = 0; i < jsonArray.size(); i++) {
                        ActivityBannerBean bean = JsonUtil.getGson().fromJson(jsonArray.get(i), ActivityBannerBean.class);
                        mActivityList.add(bean);
                    }
                    bindActivitys();
                } else {
                    ToastUtils.showShort(response.getMessage());
                    rvActivitys.setVisibility(View.GONE);
                }
            }
        };
        ApiMethodGuide.getActivityProgress(new SimpleLbObserver(listener, otherListener), null, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestGetAlipayAccount() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    AlipayAccountBean accountBean = (AlipayAccountBean) JsonUtil.getObject(response.getReturnContent(), AlipayAccountBean.class);
                    if (accountBean.getReceiveAccount() != null) {
                        tvAccount.setText("收款账户  " + accountBean.getReceiveAccount());
                        tvAccount.setBackgroundColor(mContext.getResources().getColor(R.color.transparent));
                        isBindAlipay = true;
                    } else {
                        tvAccount.setText("去绑定支付宝");
                        tvAccount.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.bg_rec_home_account_not_bind));
                        isBindAlipay = false;
                    }
                }
            }
        };
        ApiMethodGuide.getAlipayAccount(new SimpleLbObserver(listener, otherListener), null, FragmentEvent.DESTROY_VIEW);
    }


    private void sendRequestGetStaffInfo() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    UserBean userBean = (UserBean) JsonUtil.getObject(response.getReturnContent(), UserBean.class);
                    ImageLoaderUtils.displayCircle(mContext, ivAvatar, userBean.getStaffHeadPicUrl());
                    tvName.setText(userBean.getStaffName());
                }
            }
        };
        ApiMethodGuide.getStaffInfo(new SimpleLbObserver(listener, otherListener), mUserConfigManager.getUserId(), null, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestGetIntervalHint() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    if (!response.getReturnContent().equals(0.0)) {
                        showZoneToast();
                    }
                }
            }
        };
        ApiMethodGuide.getIntervalHint(new SimpleLbObserver(listener, otherListener), null, FragmentEvent.DESTROY_VIEW);
    }


    private void sendRequestGetMaterial() {
        /**
         *  "helpPicUrl": "http://static.storeer.com/wlwb/helpPicrl/04e3b2e0-1f58-46a1-9f4b-37c3e5ff869a1542592971040", // 帮助中心图片url
         *     "helpPicLink": null, // 帮助中心图片链接
         *     "videoUrl": "https://v.qq.com/x/cover/82tnyho7rqlz8z3.html" // 推手宣传视频url
         */
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JSONObject jsonObject = JsonUtil.getJsonObjectFromMap(response.getReturnContent());
                    try {
                        if (jsonObject.has("helpPicUrl")) {
                            String helpPicUrl = jsonObject.getString("helpPicUrl");
                        }
                        if (jsonObject.has("helpPicLink")) {
                            String helpPicLink = jsonObject.getString("helpPicLink");
                        }
                        if (jsonObject.has("videoUrl")) {
//                            videoUrl = jsonObject.getString("videoUrl");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        ApiMethodGuide.getMaterialUrl(new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshaActivity(ActivityFinishEvent event) {
        mActivityList = new ArrayList<>();
        sendRequestGetActivityProgress();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void bindAlipaySuccess(BindAlipayEvent event) {
        sendRequestGetAlipayAccount();
    }


    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}
